package com.mj.linkedlist.single;


import com.mj.linkedlist.AbstractList;

/**
 * @Author: LDeng
 * @Date: 2021-02-19 15:12
 * 增加虚拟头节点
 */
public class SingleLinkedList2<E> extends AbstractList<E> {

    private Node<E> first;

    public SingleLinkedList2() {
        first = new Node<>(null, null);
    }


    private static class Node<E> {
        E element;
        Node<E> next;

        public Node(E element, Node<E> next) {
            this.element = element;
            this.next = next;
        }
    }

    @Override
    public void clear() {
        size = 0;
        first = null;
    }

    @Override
    public void add(int index, E element) {

        Node<E> previous = index == 0 ? first : getNodeByIndex(index - 1);//index 0 ， 前一个节点就是虚拟头节点
                                                                         // index 非0 ，前一个节点就是index-1节点
        Node<E> newNode = new Node<E>(element, previous.next);//新节点的next指向previous的next节点
        previous.next = newNode;//将前一个节点的next指向这个新节点
        size++;
    }

    @Override
    public E remove(int index) {
        Node<E> previous = index == 0 ? first : getNodeByIndex(index - 1);
        Node<E> node = previous.next;
        previous.next = node.next;
        size--;
        return node.element;
    }

    @Override
    public int indexOf(E element) {
        if (element == null) {
            Node<E> node = first;
            for (int i = 0; i < size; i++) {
                if (node.element == null) return i;
                node = node.next;
            }
        } else {
            Node<E> node = first;
            for (int i = 0; i < size; i++) {
                if (element.equals(node.element)) return i;
                node = node.next;
            }
        }
        return ELEMENT_NOT_FOUND;
    }

    @Override
    public E get(int index) {
        return getNodeByIndex(index).element;
    }

    @Override
    public E set(int index, E element) {
        Node<E> node = getNodeByIndex(index);
        E old = node.element;
        node.element = element;
        return old;
    }

    //获取索引位置的节点对象
    private Node<E> getNodeByIndex(int index) {
        rangeCheck(index);
        Node<E> node = first.next;
        for (int i = 0; i < index; i++) {
            node = node.next;
        }
        return node;
    }

    @Override
    public String toString() {
        StringBuilder string = new StringBuilder();
        string.append("size=").append(size).append(", [");
        Node<E> node = first.next;
        for (int i = 0; i < size; i++) {
            if (i != 0) {
                string.append(", ");
            }
            string.append(node.element);
            node = node.next;
        }
        string.append("]");
        return string.toString();
    }
}
